package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.ExcelExportUtils;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.MallBalanceAccountExportHelper;
import com.rockcent.mall.helper.RetrofitHelper;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MerchantOrderMerchantRole;
import com.rockcent.mall.lib.domain.enumclass.ProductShippingType;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MallWechatApiService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import retrofit2.Response;
import retrofit2.Retrofit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/11/18.
 * 平台订单模块
 */
@RestController
public class MallOrderController extends BaseController{

    private static final Logger log = LoggerFactory.getLogger(MallOrderController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MerchantOrderRepository merchantOrderRepository;

    @Autowired
    private OrderEventRepository orderEventRepository;

    @Autowired
    private MerchantOrderItemRepository merchantOrderItemRepository;

    @Autowired
    private MerchantStoreRepository merchantStoreRepository;

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private MarketOrderRepository marketOrderRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;

    @Autowired
    private MallOrderRepository mallOrderRepository;

    private MallWechatApiService mallWechatApiService;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MallBalanceAccountExportHelper mallBalanceAccountExportHelper;

    /**
     * @api {get} /mall/order/page 平台 订单管理 分页
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {String=ALL("全部订单状态"), WAIT_PAYING("未付款"), WAIT_SHIPPED("待发货"), WAIT_SHOP_PICKUP("待自提"), SHIPPED("代签收"), APPLY_REFUND("待退款"), WAIT_USE("待使用"), FINISHED("已完成"), CANCEL("已取消")} status <code>必要参数</code> 默认ALL 订单状态
     * @apiParam {String} orderNum 订单号
     * @apiParam {String} shoppingManPhone 买家手机号
     * @apiParam {String=ALL("全部订单类型"), GOODS("商品订单"), SERVICE("服务订单"), SHOP_PICKUP("自提订单")} orderType <code>必要参数</code> 默认ALL 订单类型
     * @apiParam {String=ALL("全部订单来源"), MARKET("全部"), SELF("自营下单"), B2D("供应商"), D2C("分销商")} sourceType <code>必要参数</code> 默认ALL 订单来源
     * @apiParam {Date} beginDate 开始时间
     * @apiParam {Date} endDate 结束时间
     *
     * @apiSuccess {Long} id 订单ID
     * @apiSuccess {String} customerName 买家名称
     * @apiSuccess {String} shoppingManPhone 买家手机号码
     * @apiSuccess {BigDecimal} totalAmount 总金额
     * @apiSuccess {BigDecimal} discountAmount 优惠金额
     * @apiSuccess {Date} dateCreated 下单时间
     * @apiSuccess {String} orderNum 订单号
     * @apiSuccess {String=WAIT_PAYING("未付款"), CANCEL("取消"), PAYED("已支付"), WAIT_SHIPPED("待发货"), SHIPPED("代签收"), WAIT_SHOP_PICKUP("到店自提"), PART_SHOP_PICKUP("部分到店自提"), CONFIRM_PICKUP("确认自提"), CONFIRM("已确认"), WAIT_USE("待使用"), PART_USE("部分使用"), USED("已使用"), FINISHED("已完成"), APPLY_REJECT("申请退货"), FINISHED_REJECT("已完成退货"), APPLY_REFUND("申请退款"), FINISHED_REFUND("已完成退款"} status 订单号
     * @apiSuccess {String} remark 订单备注
     * @apiSuccess {String=SHOP_PICKUP("到店自提"), SHIPPING("物流")} productShoppingType 配送类型
     * @apiSuccess {String=SELF("自营下单"), MARKET("分销下单")} sourceType 是否分销订单
     * @apiSuccess {String=GOODS("实物商品"), SERVICE("到店服务")} orderType 订单类型
     * @apiSuccess {String} logisticsCode 物流公司编码
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String=SELF("默认"),SUPPLIER("供应商"), DISTRIBUTOR("分销商")} merchantRole 商家角色 当订单为分销订单时,用于区分供应商或者分销商
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "id": 23,
     *      "customerName": "张三",
     *      "shoppingManPhone": "15023342245",
     *      "totalAmount": "234.12",
     *      "discountAmount": "234.12",
     *      "dateCreated": "2016-08-11 16:27:32",
     *      "orderNum": "2343224",
     *      "status": "SHIPPED",
     *      "productShoppingType": "SHIPPING",
     *      "sourceType": "SELF",
     *      "orderType": "SERVICE",
     *      "merchantName": "张三",
     *      "merchantRole": "self"
     *  },
     *  .....
     * }
     */
    @RequestMapping(value = Routes.MALL_ORDER_PAGE, method = RequestMethod.GET)
    public JsonResult mallOrderPage(HttpServletRequest request, MerchantOrderDto dto){
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getSourceType())) {
                jsonResult.remind("订单状态 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getStatus())) {
                jsonResult.remind("订单类型 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getOrderType())) {
                jsonResult.remind("订单来源 不能为空",log);
                return;
            }
            PageResult<MerchantOrder> pageResult = merchantOrderRepository.findMallOrderPage(userDto.mall.getId(), dto, this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.data.stream().map(merchantOrder -> {
                //供应商,看到的买家名称为分销商
                if (MerchantOrderMerchantRole.SUPPLIER == merchantOrder.getMerchantRole()) {
                    MarketOrder marketOrder = marketOrderRepository.findByOrderNum(merchantOrder.getMarketOrderNum());
                    merchantOrder.setCustomerName(marketOrder.getDistributorMerchantName());
                    MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(marketOrder.getDistributorMerchantId(), marketOrder.getDistributorMallId());
                    merchantOrder.setShoppingManPhone(merchantCertify.getContactPhone());
                }
                return merchantOrder;
            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MALL_ORDER_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/order/info 平台 订单管理 明细
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {Long} id 订单ID
     *
     * @apiSuccess {Long} id 订单ID
     * @apiSuccess {String} customerName 买家名称
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {BigDecimal} totalAmount 总金额
     * @apiSuccess {BigDecimal} discountAmount 优惠金额
     * @apiSuccess {Date} dateCreated 下单时间
     * @apiSuccess {Date} lastUpdated 交易完成时间
     * @apiSuccess {String} orderNum 订单号
     * @apiSuccess {String} shoppingMan 收货人
     * @apiSuccess {String} shoppingAddress 收货人地址
     * @apiSuccess {String} shoppingManPhone 联系方式(自提信息也用这个联系方式)
     * @apiSuccess {String=WECHAT("微信支付"),BALANCE("余额支付")} paymentMethod 支付方式
     * @apiSuccess {String=WAIT_PAYING("未付款"), CANCEL("取消"), PAYED("已支付"), WAIT_SHIPPED("待发货"), SHIPPED("代签收"), WAIT_SHOP_PICKUP("到店自提"), PART_SHOP_PICKUP("部分到店自提"), CONFIRM_PICKUP("确认自提"), CONFIRM("已确认"), WAIT_USE("待使用"), PART_USE("部分使用"), USED("已使用"), FINISHED("已完成"), APPLY_REJECT("申请退货"), FINISHED_REJECT("已完成退货"), APPLY_REFUND("申请退款"), FINISHED_REFUND("已完成退款"} status 订单号
     * @apiSuccess {String} remark 买家备注
     * @apiSuccess {String=SHOP_PICKUP("到店自提"), SHIPPING("物流")} productShoppingType 配送方式
     * @apiSuccess {String=SELF("自营下单"), MARKET("分销下单")} sourceType 是否分销订单
     * @apiSuccess {String=GOODS("实物商品"), SERVICE("到店服务")} orderType 订单类型
     * @apiSuccess {String} logisticsNumber 物流编号
     * @apiSuccess {String} logisticsName 物流公司
     * @apiSuccess {String} address 自提地点(物流店址)
     * @apiSuccess {String} customerName 提货人
     * @apiSuccess {String=SELF("默认"),SUPPLIER("供应商"), DISTRIBUTOR("分销商")} merchantRole 商家角色 当订单为分销订单时,用于区分供应商或者分销商
     *
     * @apiSuccess {Date} orderEventList_dateCreated 订单跟踪 时间
     * @apiSuccess {String} orderEventList_remark 订单跟踪 处理信息
     * @apiSuccess {String} orderEventList_operator 订单跟踪 操作人
     *
     * @apiSuccess {String} merchantOrderItemList_productId 产品信息 编号
     * @apiSuccess {String} merchantOrderItemList_productName 产品信息 产品
     * @apiSuccess {String} merchantOrderItemList_buyCount 产品信息 数量
     * @apiSuccess {String} merchantOrderItemList_singleAmount 产品信息 单价
     * @apiSuccess {String} merchantOrderItemList_totalAmount 产品信息 总价
     * @apiSuccess {String} merchantOrderItemList_discountAmount 产品信息 优惠金额
     * @apiSuccess {String} merchantOrderItemList_resellerName 产品信息 所属商家
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "id": 23,
     *      "customerName": "张三",
     *      "merchantName": "张三",
     *      "shoppingManPhone": "15023342245",
     *      "amount": "234.12",
     *      "discountAmount": "234.12",
     *      "dateCreated": "2016-08-11 16:27:32",
     *      "lastUpdated": "2016-08-11 16:27:32",
     *      "orderNum": "2343224",
     *      "shoppingMan": "张三",
     *      "shoppingAddress": "广东设个",
     *      "shoppingManPhone": "15023342245",
     *      "status": "SHIPPED",
     *      "paymentMethod": "WECHAT",
     *      "productShoppingType": "SHIPPING",
     *      "sourceType": "SELF",
     *      "orderType": "SERVICE",
     *      "remark": "到店服务",
     *      "logisticsNumber": "234234234",
     *      "logisticsName": "顺丰",
     *      "merchantRole": "self",
     *      "orderEventList" :[{
     *          "dateCreated" : 2342,
     *          "remark" : "黄色",
     *          "operator" : "里斯"
     *      },
     *      ........
     *      ],
     *      "merchantOrderItemList" :[{
     *          "productId" : 2342,
     *          "productName" : "黄色",
     *          "resellerName" : "黄色",
     *          "buyCount" : "234",
     *          "singleAmount" : "34.2",
     *          "totalAmount" : "342",
     *          "discountAmount" : "2342"
     *      },
     *      ........
     *      ]
     *  },
     *  .....
     * }
     */
    @RequestMapping(value = Routes.MALL_ORDER_INFO, method = RequestMethod.GET)
    public JsonResult mallOrderInfo(HttpServletRequest request, MerchantOrderDto dto){
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MerchantOrder.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MerchantOrder merchantOrder = merchantOrderRepository.findByIdAndMallId(dto.getId(), userDto.mall.getId());
            if (merchantOrder == null) {
                jsonResult.remind(MerchantOrder.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }


            RBeanUtils.copyProperties(merchantOrder, dto);

            dto.setStatus(merchantOrder.getStatus().toString());
            dto.setProductShoppingType(merchantOrder.getProductShoppingType().toString());
            dto.setOrderType(merchantOrder.getOrderType().toString());
            if (merchantOrder.getPaymentMethod() != null) {
                dto.setPaymentMethod(merchantOrder.getPaymentMethod().toString());
            }
            //订单事件
            List<OrderEvent> orderEventList = orderEventRepository.findByMerchantOrderNumAndMallOrderNum(merchantOrder.getOrderNum(), merchantOrder.getMallOrderNum());
            dto.setOrderEventList(orderEventList);
            //订单包含产品
            List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderId(merchantOrder.getId());
            merchantOrderItemList.stream().forEach(merchantOrderItem -> {
               Merchant merchant =  merchantRepository.findOne(merchantOrderItem.getMerchantId());
                merchantOrderItem.setResellerName(merchant.getName());
            });
            dto.setMerchantOrderItemList(merchantOrderItemList);

            if (ProductShippingType.SHIPPING == merchantOrder.getProductShoppingType()) {
                dto.setAddress(merchantOrder.getShoppingAddress());
            }

            //供应商,看到的买家名称为分销商
            if (MerchantOrderMerchantRole.SUPPLIER == merchantOrder.getMerchantRole()) {
                MarketOrder marketOrder = marketOrderRepository.findByOrderNum(merchantOrder.getMarketOrderNum());
                MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(marketOrder.getDistributorMerchantId(), marketOrder.getDistributorMallId());
                merchantOrder.setShoppingManPhone(merchantCertify.getContactPhone());
                merchantOrder.setCustomerName(marketOrder.getDistributorMerchantName());
            }

//            if (ProductShippingType.SHOP_PICKUP == merchantOrder.getProductShoppingType()) {
//                if (merchantOrder.getMerchantStoreId() != null) {
//                    MerchantStore merchantStore = merchantStoreRepository.findOne(merchantOrder.getMerchantStoreId());
//                    Customer customer = customerRepository.findOne(merchantOrder.getCustomerId());
//                    if (customer != null) {
//                        dto.setShoppingManPhone(customer.getMobile());
//                    }
//                    dto.setAddress(merchantStore.getLocationStr() + merchantStore.getAddress());
//                }
//            }
            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/balance/account/page 平台 平台对账单 概要 分页
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {String} orderNum 平台订单号
     * @apiParam {String} beginDate 开始时间
     * @apiParam {String} endDate 结束时间
     *
     * @apiSuccess {Long} customerId 客户id
     * @apiSuccess {String} orderNum 平台订单号
     * @apiSuccess {String} paymentTransaction 交易流水号
     * @apiSuccess {BigDecimal} actualAmount 实付金额
     * @apiSuccess {Date} dateCreated 下单时间
     *
     * @apiSuccess {String=GOODS("商品"), SERVICE("服务")} merchantOrderList_orderType 明细 订单类型
     * @apiSuccess {String=SELF("默认"),SUPPLIER("供应商"), DISTRIBUTOR("分销商")} merchantOrderList_merchantRole 明细 商家角色
     * @apiSuccess {String} merchantOrderList_merchantName 明细 供应商名称(分销商名称)
     * @apiSuccess {String} merchantOrderList_merchantId 明细 供应商ID(分销商ID)
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "customerId": "张三",
     *      "orderNum": "23534245",
     *      "paymentTransaction": "23434t455",
     *      "actualAmount": "15023342245",
     *      "dateCreated": "2016-08-11 16:27:32"
     *      },
     *      .....
     * }
     */
    @RequestMapping(value = Routes.MALL_BALANCE_ACCOUNT_PAGE, method = RequestMethod.GET)
    public JsonResult mallBalanceAccount(HttpServletRequest request, MallOrderDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isNotBlank(dto.getBeginDate()) && StringUtils.isNotBlank(dto.getEndDate())) {
                if (RDateUtils.parseDate(dto.getBeginDate(), "yyyy-MM-dd").getTime() > RDateUtils.parseDate(dto.getEndDate(), "yyyy-MM-dd").getTime()) {
                    jsonResult.remind("开始时间不能大于结束时间",log);
                    return;
                }
            }
            PageResult<MallOrderDto> pageResult = mallOrderRepository.findMallBalanceAccount(dto.getBeginDate(), dto.getEndDate(), userInfoDto.mall.getId(), dto.getOrderNum(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/balance/account/info/page 平台 平台对账单 明细 分页
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {String} orderNum 平台订单号
     * @apiParam {String} beginDate 开始时间
     * @apiParam {String} endDate 结束时间
     *
     * @apiSuccess {Long} customerId 客户id
     * @apiSuccess {String} orderNum 平台订单号
     * @apiSuccess {String} paymentTransaction 交易流水号
     * @apiSuccess {BigDecimal} actualAmount 实付金额
     * @apiSuccess {Date} dateCreated 下单时间
     *
     * @apiSuccess {String} merchantOrderDtoList_merchantName 商家名称
     * @apiSuccess {String=SHOP_PICKUP("到店自提"), SHIPPING("物流")} merchantOrderDtoList_productShoppingType 物流种类
     * @apiSuccess {String=GOODS("商品"), SERVICE("服务")} merchantOrderDtoList_orderType 订单类型
     *
     *
     * @apiSuccess {String=B2C("一般订单"), B2C2C("分享订单"), B2D2C("分销订单"), B2D2C2C("分销分享订单")} merchantOrderItemList_pathType 订单类型
     * @apiSuccess {String=SELF("默认"),SUPPLIER("供应商"), DISTRIBUTOR("分销商")} merchantOrderItemList_merchantRole 商家角色
     * @apiSuccess {String} merchantOrderItemList_supplierMerchantId 供应商ID
     * @apiSuccess {String} merchantOrderItemList_supplierMerchantName 供应商名称
     * @apiSuccess {String} merchantOrderItemList_distributorMerchantId 分销商ID
     * @apiSuccess {String} merchantOrderItemList_distributorMerchantName 分销商名称
     * @apiSuccess {String} merchantOrderItemList_sharerId 分享者ID
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "customerId": "张三",
     *      "orderNum": "23534245",
     *      "paymentTransaction": "23434t455",
     *      "actualAmount": "15023342245",
     *      "dateCreated": "2016-08-11 16:27:32",
     *      "merchantOrderDtoList" :[
     *          {
     *          "merchantName" : "里斯",
     *          "productShoppingType" : "里斯",
     *          "orderType" : "GOODS",
     *          "merchantOrderItemList" : [
     *              {
     *                  "pathType" : "B2C",
     *                  "merchantRole" : "SELF",
     *                  "supplierMerchantId" : 12,
     *                  "supplierMerchantName" : "占三",
     *                  "distributorMerchantId" : 123,
     *                  "distributorMerchantName" : "里斯",
     *                  "sharerId" : 23,
     *              },
     *              .....
     *          ]
     *          },
     *         ........
     *      ]
     *      },
     *      .....
     * }
     */
    @RequestMapping(value = Routes.MALL_BALANCE_ACCOUNT_INFO_PAGE, method = RequestMethod.GET)
    public JsonResult mallBalanceAccountInfo(HttpServletRequest request, MallOrderDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isNotBlank(dto.getBeginDate()) && StringUtils.isNotBlank(dto.getEndDate())) {
                if (RDateUtils.parseDate(dto.getBeginDate(), "yyyy-MM-dd").getTime() > RDateUtils.parseDate(dto.getEndDate(), "yyyy-MM-dd").getTime()) {
                    jsonResult.remind("开始时间不能大于结束时间",log);
                    return;
                }
            }
            PageResult<MallOrderDto> pageResult = mallOrderRepository.findMallBalanceAccount(dto.getBeginDate(), dto.getEndDate(), userInfoDto.mall.getId(), dto.getOrderNum(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.data.stream().map(mallOrder -> {
                List<MerchantOrderDto> merchantOrderDtoList = merchantOrderRepository.findMallBalanceAccountInfo(userInfoDto.mall.getId(), mallOrder.getOrderNum());
                merchantOrderDtoList.stream().map(merchantOrder ->{
                    List<MerchantOrderItemDto> merchantOrderItemList = merchantOrderItemRepository.findMerchantOrderItemList(merchantOrder.getId());
                    merchantOrderItemList.stream().map(merchantOrderItem -> {
                        merchantOrderItem.setSupplierMerchantId(merchantOrder.getMerchantId());
                        merchantOrderItem.setSupplierMerchantName(merchantOrder.getMerchantName());
                        //分销订单
                        if (MerchantOrderMerchantRole.DISTRIBUTOR == MerchantOrderMerchantRole.valueOf(merchantOrderItem.getMerchantRole())) {
                            MerchantOrder order = merchantOrderRepository.findByMarketOrderNumAndMerchantRole(merchantOrderItem.getMarketOrderNum(), MerchantOrderMerchantRole.SUPPLIER);
                            if (order != null) {
                                merchantOrderItem.setSupplierMerchantId(order.getMerchantId());
                                merchantOrderItem.setSupplierMerchantName(order.getMerchantName());
                            }
                            merchantOrderItem.setDistributorMerchantId(merchantOrder.getMerchantId());
                            merchantOrderItem.setDistributorMerchantName(merchantOrder.getMerchantName());
                        }
                        return merchantOrderItem;
                    }).collect(Collectors.toList());
                    merchantOrder.setMerchantOrderItemDtoList(merchantOrderItemList);
                    return merchantOrder;
                }).collect(Collectors.toList());
                mallOrder.setMerchantOrderDtoList(merchantOrderDtoList);
                return mallOrder;
            }).collect(Collectors.toList());
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/query/wechat/order 平台 查询微信订单
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {String} orderNum <code>必要参数</code> 平台订单号
     * @apiParam {String} paymentTransaction <code>必要参数</code> 支付流水号
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "customerId": "张三",
     *      "orderNum": "张三",
     *      "discountTotalAmount": "15023342245",
     *      "dateCreated": "2016-08-11 16:27:32",
     *      },
     *      .....
     * }
     */
    @RequestMapping(value = Routes.MALL_QUERY_WECHAT_ORDER, method = RequestMethod.GET)
    public JsonResult findWechatBalanceAccount(HttpServletRequest request, MallOrderDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getOrderNum())) {
                jsonResult.remind("平台订单号 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getPaymentTransaction())) {
                jsonResult.remind("支付流水号 不能为空",log);
                return;
            }
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            String domain = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(domain)) {
                domain = mall.getMobileHostName();
            }
            String url = "http://127.0.0.1:8881";
            Retrofit retrofit = RetrofitHelper.SINGLETON.getRetrofit(url);
            mallWechatApiService = retrofit.create(MallWechatApiService.class);
            Response<JsonResult> transactionDto = mallWechatApiService.wechatOrderQuery(domain, dto.getPaymentTransaction(), dto.getOrderNum()).execute();
            jsonResult.data = transactionDto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/balance/account/detail/export 平台 平台对账单 明细 excel报表导出
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {String} orderNum 平台订单号
     * @apiParam {String} beginDate 开始时间
     * @apiParam {String} endDate 结束时间
     *
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *      "code": "1",
     *      "desc": "成功"
     *  }
     */
    @RequestMapping(value = Routes.MALL_BALANCE_ACCOUNT_DETAIL_EXPORT, method = RequestMethod.GET)
    public JsonResult mallBalanceAccountDetailExport (HttpServletRequest request, HttpServletResponse response, MallOrderDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isNotBlank(dto.getBeginDate()) && StringUtils.isNotBlank(dto.getEndDate())) {
                if (RDateUtils.parseDate(dto.getBeginDate(), "yyyy-MM-dd").getTime() > RDateUtils.parseDate(dto.getEndDate(), "yyyy-MM-dd").getTime()) {
                    jsonResult.remind("开始时间不能大于结束时间",log);
                    return;
                }
            }
            List<MallOrderDto> mallOrderList = mallOrderRepository.mallBalanceAccountExport(dto.getBeginDate(), dto.getEndDate(), userInfoDto.mall.getId(), dto.getOrderNum());
            mallOrderList.stream().map(mallOrder -> {
                List<MerchantOrderDto> merchantOrderDtoList = merchantOrderRepository.findMallBalanceAccountInfo(userInfoDto.mall.getId(), mallOrder.getOrderNum());
                merchantOrderDtoList.stream().map(merchantOrder ->{
                    List<MerchantOrderItemDto> merchantOrderItemList = merchantOrderItemRepository.findMerchantOrderItemList(merchantOrder.getId());
                    merchantOrderItemList.stream().map(merchantOrderItem -> {
                        merchantOrderItem.setSupplierMerchantId(merchantOrder.getMerchantId());
                        merchantOrderItem.setSupplierMerchantName(merchantOrder.getMerchantName());
                        //分销订单
                        if (MerchantOrderMerchantRole.DISTRIBUTOR == MerchantOrderMerchantRole.valueOf(merchantOrderItem.getMerchantRole())) {
                            MerchantOrder order = merchantOrderRepository.findByMarketOrderNumAndMerchantRole(merchantOrderItem.getMarketOrderNum(), MerchantOrderMerchantRole.SUPPLIER);
                            merchantOrderItem.setDistributorMerchantId(merchantOrder.getMerchantId());
                            merchantOrderItem.setDistributorMerchantName(merchantOrder.getMerchantName());
                            if (order != null) {
                                merchantOrderItem.setSupplierMerchantId(order.getMerchantId());
                                merchantOrderItem.setSupplierMerchantName(order.getMerchantName());
                            }
                        }
                        return merchantOrderItem;
                    }).collect(Collectors.toList());
                    merchantOrder.setMerchantOrderItemDtoList(merchantOrderItemList);
                    return merchantOrder;
                }).collect(Collectors.toList());
                mallOrder.setMerchantOrderDtoList(merchantOrderDtoList);
                return mallOrder;
            }).collect(Collectors.toList());
            //excel报表导出
            mallBalanceAccountExportHelper.mallBalanceAccountExportExcel(mallOrderList, response);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/balance/account/general/export 平台 平台对账单 概要 excel报表导出
     * @apiGroup MALL_ORDER
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken <code>必要参数</code> 用户token
     * @apiHeader {String} domain <code>必要参数</code> 请求域名
     *
     * @apiParam {String} orderNum 平台订单号
     * @apiParam {String} beginDate 开始时间
     * @apiParam {String} endDate 结束时间
     *
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *      "code": "1",
     *      "desc": "成功"
     *  }
     */
    @RequestMapping(value = Routes.MALL_BALANCE_ACCOUNT_GENERAL_EXPORT, method = RequestMethod.GET)
    public JsonResult mallBalanceAccountExport(HttpServletRequest request, HttpServletResponse response, MallOrderDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isNotBlank(dto.getBeginDate()) && StringUtils.isNotBlank(dto.getEndDate())) {
                if (RDateUtils.parseDate(dto.getBeginDate(), "yyyy-MM-dd").getTime() > RDateUtils.parseDate(dto.getEndDate(), "yyyy-MM-dd").getTime()) {
                    jsonResult.remind("开始时间不能大于结束时间",log);
                    return;
                }
            }
            List<MallOrderDto> mallOrderList = mallOrderRepository.mallBalanceAccountExport(dto.getBeginDate(), dto.getEndDate(), userInfoDto.mall.getId(), dto.getOrderNum());
            String[] title = {"平台订单号", "交易流水号", "买家ID", "实付金额", "下单时间"};
            String[] columnName = {"orderNum", "paymentTransaction", "customerId", "actualAmount", "createDate"};
            //excel报表导出
            ExcelExportUtils.excelExport(title, columnName, mallOrderList, response);
        };
        return doing.go(request, log);
    }

}
